package pers.vic.upload.socket.service;

import ch.qos.logback.core.net.SyslogOutputStream;
import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.vo.BooleanWithMsg;
import cn.xuqiudong.common.util.CnToSpellUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import pers.vic.upload.config.UploadProperties;
import pers.vic.upload.constant.FileType;
import pers.vic.upload.constant.FinalFiledParams;
import pers.vic.upload.constant.ResultEnum;
import pers.vic.upload.login.model.User;
import pers.vic.upload.socket.model.RealFile;
import pers.vic.upload.utils.SessionHelper;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 描述: 对文件进行真实的存储
 * @author Vic.xu
 * @date 2022-07-15 9:26
 */
@Service
public class FileStorageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileStorageService.class);

    @Resource
    private UploadProperties uploadProperties;


    /**
     * 创建文件     存储地址 + 临时目录 +  用户名
     * @param filename 文件名
     * @param type
     * @return RealFile
     */
    public BaseResponse<RealFile> createNewFile(String filename, FileType type) {
        User user = SessionHelper.getSocketThreadUser();
        if (user == null) {
            throw new CommonException("当前线程中不存在用户信息");
        }
        String sb = uploadProperties.getFolder() +
                File.separator +
                FinalFiledParams.TEMPORARY_FOLDER +
                File.separator +
                user.getUsername() +
                File.separator +
                type.name() +
                File.separator +
                filename;
        RealFile realFile = new RealFile(sb, type);
        File file = realFile.file();
        if (file.exists()) {
            return BaseResponse.error(ResultEnum.CURRENT_FILE_BE_UPLOADING);
        }
        //创建父文件夹
        File parentFile = file.getParentFile();
        if (!parentFile.exists() && !parentFile.mkdirs()) {
            throw new CommonException("创建文件夹" + parentFile.getAbsolutePath() + "失败");
        }

        return BaseResponse.success(realFile);
    }


    /**
     * 创建文件
     * @param file RealFile
     */
    public void touch(RealFile file) {
        try {
            FileUtils.touch(file.file());
        } catch (IOException e) {
            throw new CommonException("touch 文件失败", e);
        }
    }

    /**
     * 向磁盘文件写入内容
     * @param buffer ByteBuffer内容
     * @param writePosition 写入位置
     * @param realFile 真实文件
     * @return true or false
     */
    public boolean upLoadToStorageByByteBuff(ByteBuffer buffer, long writePosition, RealFile realFile) {
        Assert.isTrue(writePosition >= 0, "写入位置错误：" + writePosition);
        File file = realFile.file();
        if (!file.getParentFile().exists()) {
            boolean flag = file.getParentFile().mkdirs();
            LOGGER.info("追加文件方式上传，创建父文件夹 {}", flag);
        }
        try {
            FileChannelHolder holder = FileChannelHolder.get(file);
            holder.write(writePosition, buffer);
        } catch (Exception e) {
            LOGGER.error("写入文件{}失败", file, e);
            return false;
        }
        return true;
    }


}
